package exception

import (
	"gitee.com/zhucheer/orange/app"
	"gitee.com/zhucheer/orange/logger"
	"runtime/debug"
)

type PanicReader struct {
}

// NewPanicReader 捕获panic
func NewPanicReader() *PanicReader {
	return &PanicReader{}
}

// Func implements Middleware interface.
func (w PanicReader) Func() app.MiddlewareFunc {
	return func(next app.HandlerFunc) app.HandlerFunc {
		return func(c *app.Context) error {
			defer func() {
				if pr := recover(); pr != nil {
					logger.Criticalw("APP-PANIC", "panic", pr)
					c.SetPanic(pr)
					c.SetResponseStatus(500)
					c.ToString(errorHtml())
					debug.PrintStack()
					return
				}
			}()

			return next(c)
		}
	}
}

func errorHtml() string {
	errorHtml := `
<html>
<head><title>500 Internal server error</title></head>
<body>
<center><h1>500 Internal server error</h1></center>
<hr><center>orange/v0.2</center>
</body>
</html>`

	return errorHtml
}
